package com.wuzf.springcloud.controller;


import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.wuzf.common.entity.CommonResult;
import com.wuzf.springcloud.service.HystrixService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
// 全局的fallback属性
@DefaultProperties(defaultFallback = "global_default_fallback")
public class HystrixController {

    @Autowired
    private HystrixService hystrixService;

    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "500")
    })
    @PostMapping("/order/payment/ok")
    public CommonResult ok() {

        return hystrixService.ok();
    }


    /**
     * 再此方法上配置熔断策略
     *
     * @param id
     * @return
     */
    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "500"),
            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60"),
    })
    @PostMapping("/order/payment/error/{id}")
    public CommonResult error(@PathVariable("id") Integer id) {

        return hystrixService.error(id);
    }


    @HystrixCommand(fallbackMethod = "default_fallback", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
    })
    @PostMapping("/order/payment/timeout")
    public CommonResult timeout() {

        return hystrixService.timeout();
    }


    public CommonResult default_fallback() {

        return new CommonResult(100, "（单独）错误了，哭唧唧");
    }

    // 如果没有特别指定，则使用全局的服务降级
    public CommonResult global_default_fallback() {
        return new CommonResult(100, "（全局）错误了，哭唧唧");
    }
}
